<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>05_components_composing</title>
</head>
<body>

<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
    class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                todos: ['吃饭', '睡觉', '撸代码']
            };

            this.addTodo = this.addTodo.bind(this);
        }

        addTodo(todo) {
            const {todos} = this.state;
            todos.unshift(todo);
            //设置完状态还得更新回去
            this.setState({todos});
        }

        render() {
            const {todos} = this.state;
            return (
                <div>
                    <h1>Simple TODO List</h1>
                    <Add count={todos.length} addTodo={this.addTodo}/>
                    <List todos={todos}/>
                </div>
            )
        }
    }

    class Add extends React.Component {
        constructor(props) {
            super(props);

            this.handleAdd = this.handleAdd.bind(this);
        }

        handleAdd() {
            //1.读取数据
            const todo = this.content.value.trim();
            //2.校验合法性
            if (!todo) {
                return;
            }
            //3.添加数据
            this.props.addTodo(todo);
            //4.清除数据
            this.content.value = '';
        }

        render() {
            const {count} = this.props;
            return (
                <div>
                    <input type="text" ref={input => this.content = input}/>
                    <button onClick={this.handleAdd}>add #{count + 1}</button>
                </div>
            )
        }
    }

    Add.proptypes = {
        count: PropTypes.number.isRequired,
        addTodo: PropTypes.func.isRequired
    };

    class List extends React.Component {
        render() {
            const {todos} = this.props;
            return (
                <div>
                    <ul>
                        {todos.map((todo, index) => <li key={index}>{todo}</li>)}
                    </ul>
                </div>
            )
        }
    }

    List.proptypes = {
        todos: PropTypes.array.isRequired
    };

    ReactDOM.render(<App/>, document.getElementById('example'));
</script>
</body>
</html>
